<template>
    <coreshop-page title="订单详情" mode="left">
        <view class="layout-order-box">

            <!-- 步骤条区域 -->
            <view class="order-steps-box" v-if="state.orderStatus <= OrderAllStatusTypeEnum.aLL_PARTIAL_DELIVERY">
                <view class="steps-status" v-if="state.orderStatus == 0">
                    <view class="status-box">
                        <view class="tit">拍下成功</view>
                        <view class="desc">待买家支付</view>
                    </view>
                    <view class="explain">
                        <view class="tit">拍下{{ shopConfigStore?.config?.orderCancelTime || 60 }}分后</view>
                        <view class="desc">未支付，自动取消订单。</view>
                    </view>
                </view>
                <view class="steps-status" v-if="state.orderStatus == OrderAllStatusTypeEnum.aLL_PENDING_PAYMENT">
                    <view class="status-box">
                        <view class="tit">支付成功</view>
                        <view class="desc">待卖家发货</view>
                    </view>
                </view>
                <view class="steps-status" v-if="state.orderStatus == OrderAllStatusTypeEnum.aLL_PENDING_DELIVERY">
                    <view class="status-box">
                        <view class="tit">已发货</view>
                        <view class="desc">快递正在路上</view>
                    </view>
                    <view class="explain">
                        <view class="tit">务必在收到商品后再确认收货。</view>
                        <view class="desc">发货20天后将自动确认收货</view>
                    </view>
                </view>
                <view class="steps-status" v-if="state.orderStatus == OrderAllStatusTypeEnum.aLL_PENDING_RECEIPT">
                    <view class="status-box">
                        <view class="tit">已收货</view>
                        <view class="desc">请您对此次购物体检进行评价</view>
                    </view>
                    <view class="explain">
                        <view class="tit">收货30天后将自动评价</view>
                    </view>
                </view>
                <view class="steps-status" v-if="state.orderStatus == OrderAllStatusTypeEnum.aLL_PENDING_EVALUATE">
                    <view class="status-box">
                        <view class="tit">交易成功</view>
                        <view class="desc">感谢您的评价</view>
                    </view>
                </view>
                <view class="steps-status" v-if="state.orderStatus == OrderAllStatusTypeEnum.aLL_COMPLETED">
                    <view class="status-box">
                        <view class="tit">交易成功</view>
                        <view class="desc">期待下次服务</view>
                    </view>
                </view>
                <view class="steps-status" v-if="state.orderStatus == OrderAllStatusTypeEnum.aLL_CANCEL">
                    <view class="status-box">
                        <view class="tit">订单已取消</view>
                    </view>
                </view>
                <view class="steps-box" v-if="state.orderStatus < OrderAllStatusTypeEnum.aLL_COMPLETED_EVALUATE">
                    <uv-steps activeColor="#D33123" inactiveColor="#999" :current="state.orderStatus">
                        <uv-steps-item title="下单"></uv-steps-item>
                        <uv-steps-item title="付款"></uv-steps-item>
                        <uv-steps-item title="发货"></uv-steps-item>
                        <uv-steps-item title="收货"></uv-steps-item>
                        <uv-steps-item title="评价"></uv-steps-item>
                    </uv-steps>
                </view>
            </view>

            <!-- 拼团信息 -->
            <view class="order-msg"
                v-if="state.orderDetail?.orderType == 2 && state.orderDetail?.status != OrderStatusEnum.cancel && state.orderDetail?.payStatus != OrderPayStatusEnum.no">
                <view class="title">
                    <text v-if="state.teamInfo?.status == PinTuanStatusEnum.pending">待拼团，还差{{ state.teamInfo?.teamNums
                        || '' }}人</text>
                    <text v-if="state.teamInfo?.status == PinTuanStatusEnum.complete">拼团成功，待发货</text>
                    <text v-if="state.teamInfo?.status == PinTuanStatusEnum.cancel">拼团失败</text>
                </view>
                <view class="pinTuan-box">
                    <view class="pinTuan-peo" v-if="state.teamInfo?.teams?.length > 0">
                        <view class="img-box" v-for="item, index in state.teamInfo?.teams" :key="index">
                            <image class="img" :src="item.userAvatar"></image>
                            <text class="tag" v-if="item.recordId == state.teamInfo?.teamId">拼主</text>
                        </view>
                        <view class="img-box" v-if="state.teamInfo?.teamNums > 3">
                            <view class="avatar" v-for="n in 3" :key="n">?</view>
                            <view class="avatar">···</view>
                        </view>
                        <view class="img-box" v-else>
                            <view class="avatar">?</view>
                        </view>
                    </view>
                    <view class="share-box">
                        <uv-button type="success" size="small" @click="handleInviteFriends">
                            <uv-icon name="share" color="#fff" labelColor="#fff" label="立即邀请好友拼单" labelSize="14px"
                                labelPos="right" size="18"></uv-icon>
                        </uv-button>
                    </view>
                </view>
            </view>

            <!-- 物流信息 -->
            <view class="order-msg" v-if="state.orderStatus != 0 && !state.orderDetail?.store">
                <view class="title">
                    <view class="tit">物流信息</view>
                    <view class="desc" v-if="state.orderStatus == 2">已发货，请注意查收</view>
                </view>
                <view class="logistics-box">
                    <view class="name-box">
                        <view class="name">收货人：{{ state.orderDetail?.shipName || '' }}</view>
                        <view class="phone">{{ state.orderDetail?.shipMobile || '' }}</view>
                    </view>
                    <view class="address">收货人地址：{{ state.orderDetail?.shipAreaName || '' }}
                        {{ state.orderDetail?.shipAddress || '' }}
                    </view>
                </view>
                <view class="logistics-num" v-if="state.orderDetail?.delivery?.length > 0">
                    <view class="logistics" v-for="item, index in state.orderDetail?.delivery" :key="index">
                        <view class="item">
                            <view class="lab">物流名称：</view>
                            <view class="val">{{ item.logiName }}</view>
                            <view class="view" @click="handleViewLogistics(item)">查看物流信息</view>
                        </view>
                        <view class="item">
                            <view class="lab">物流单号：</view>
                            <view class="val">{{ item.logiNo }}</view>
                            <view class="copy" @click="handleCopyLogiNo(item.logiNo)">复制单号</view>
                        </view>
                        <view class="item">
                            <view class="lab">发货时间：</view>
                            <view class="val">{{ item.createTime }}</view>
                        </view>
                    </view>
                </view>
            </view>

            <!-- 提货信息 -->
            <view class="order-msg" v-if="state.orderDetail?.store">
                <view class="title">提货信息</view>
                <view class="order-box">
                    <view class="msg-box">
                        <view class="lab">提货门店</view>
                        <view class="val">{{ state.orderDetail?.store?.storeName || '无' }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">门店电话</view>
                        <view class="val">{{ state.orderDetail?.store?.mobile || '无' }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">门店地址</view>
                        <view class="val">{{ state.orderDetail?.store?.address || '无' }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">提货人信息</view>
                        <view class="val">{{ state.orderDetail?.shipName || '' }} - {{ state.orderDetail?.shipMobile ||
                            '' }}</view>
                    </view>
                    <view class="msg-box" v-if="state.pickupCode">
                        <view class="lab">提货码</view>
                        <view class="val red" @click="handleViewCode">{{ state.pickupCode }}</view>
                    </view>
                </view>
            </view>
            <!-- 提货码弹框 -->
            <uv-popup ref="codePopup" mode="center" :safeAreaInsetBottom="false"
                :customStyle="{'border-radius':'15rpx'}">
                <view class="code-box">
                    <canvas canvas-id="qrcode" style="width: 200px; height: 200px;" />
                    <image v-if="state.codeSrc" class="img" :src="state.codeSrc"></image>
                </view>
            </uv-popup>

            <!-- 商品信息 -->
            <view class="order-msg">
                <view class="title">商品信息</view>
                <view class="goods-box">
                    <view class="item-box" v-for="item in state.orderDetail?.items" :key="item.id">
                        <coreshop-goods-card type="horizontal" imgHeight="140rpx" imgWidth="140rpx"
                            :goodsData="hanldeCombinationGoodsData(item)">
                            <template #goodPrice>
                                <view class="goods-price">
                                    <view class="price">￥{{ item.price }}</view>
                                    <view class="num">x{{ item.nums }}</view>
                                </view>
                            </template>
                        </coreshop-goods-card>
                    </view>
                </view>
            </view>

            <!-- 发票信息 -->
            <view class="order-msg" v-if="state.orderDetail?.invoice && state.orderDetail?.invoice?.type != 1">
                <view class="title">发票信息</view>
                <view class="order-box">
                    <view class="msg-box">
                        <view class="lab">发票抬头</view>
                        <view class="val">{{ state.orderDetail?.invoice?.title || '无' }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">发票税号</view>
                        <view class="val">{{ state.orderDetail?.invoice?.taxNumber || '无' }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.invoice?.fileUrl">
                        <view class="lab">下载发票</view>
                        <view class="val">
                            <uv-tags @click="handleSaveInvoice" text="保存到本地" size="mini" type="success"></uv-tags>
                        </view>
                    </view>
                </view>
            </view>

            <!--费用信息-->
            <view class="order-msg">
                <view class="title">费用信息</view>
                <view class="order-box">
                    <view class="msg-box">
                        <view class="lab">商品总额</view>
                        <view class="val">￥{{ state.orderDetail?.goodsAmount }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">商品优惠</view>
                        <view class="val">-￥{{ state.orderDetail?.goodsDiscountAmount }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">{{ shopConfigStore?.config?.pointShowName }}优惠</view>
                        <view class="val">-￥{{ state.orderDetail?.pointMoney }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.orderDiscountAmount > 0">
                        <view class="lab">订单优惠</view>
                        <view class="val">-￥{{ state.orderDetail?.orderDiscountAmount }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.couponDiscountAmount > 0">
                        <view class="lab">优惠券优惠</view>
                        <view class="val">-￥{{ state.orderDetail?.couponDiscountAmount }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">运费</view>
                        <view class="val">+￥{{ state.orderDetail?.costFreight }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.payStatus > OrderPayStatusEnum.no">
                        <view class="lab">支付方式</view>
                        <view class="val">{{ state.orderDetail?.paymentName }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.payStatus > OrderPayStatusEnum.no">
                        <view class="lab">支付时间</view>
                        <view class="val">{{ state.orderDetail?.paymentTime }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">应付款</view>
                        <view class="val payable">￥{{ state.orderDetail?.orderAmount }}</view>
                    </view>
                </view>
            </view>

            <!-- 订单信息 -->
            <view class="order-msg">
                <view class="title">订单信息</view>
                <view class="order-box">
                    <view class="msg-box">
                        <view class="lab">订单编号</view>
                        <view class="val">{{ state.orderDetail?.orderId }}</view>
                    </view>
                    <view class="msg-box">
                        <view class="lab">订单类型</view>
                        <view class="val">{{ state.orderDetail?.typeText }}</view>
                    </view>
                    <view class="msg-box"
                        v-if="state.orderDetail?.paymentName && state.orderDetail?.payStatus > OrderPayStatusEnum.no">
                        <view class="lab">支付方式</view>
                        <view class="val">{{ state.orderDetail?.paymentName }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.createTime">
                        <view class="lab">下单时间</view>
                        <view class="val">{{ state.orderDetail?.createTime }}</view>
                    </view>
                    <view class="msg-box" v-if="state.orderDetail?.paymentTime && state.orderStatus > 0">
                        <view class="lab">支付时间</view>
                        <view class="val">{{ state.orderDetail?.paymentTime }}</view>
                    </view>
                    <view class="msg-box"
                        v-if="Object.keys(state.deliveryInfo).length > 0 && state.deliveryInfo?.createTime">
                        <view class="lab">发货时间</view>
                        <view class="val">{{ state.deliveryInfo?.createTime }}</view>
                    </view>
                    <view class="msg-box"
                        v-if="state.orderDetail?.confirmTime && state.orderStatus > OrderShipStatusEnum.partialYes">
                        <view class="lab">确认时间</view>
                        <view class="val">{{ state.orderDetail?.confirmTime }}</view>
                    </view>
                    <view class="msg-box"
                        v-if="state.orderDetail?.updateTime && state.orderStatus > OrderAllStatusTypeEnum.aLL_PENDING_RECEIPT">
                        <view class="lab">
                            <text v-if="state.orderStatus >= OrderAllStatusTypeEnum.aLL_CANCEL">取消时间</text>
                            <text v-else>完成时间</text>
                        </view>
                        <view class="val">{{ state.orderDetail?.updateTime }}</view>
                    </view>
                </view>
            </view>

            <!-- 为您推荐 -->
            <GoodsDetailRecommend></GoodsDetailRecommend>

            <!-- 底部按钮信息 -->
            <view class="layout-btn-box" v-if="!state.data">
                <view class="btn-box">
                    <view class="bottom-btn-box"
                        v-if="state.orderDetail?.status == OrderStatusEnum.pending || state.orderDetail?.status == OrderStatusEnum.complete">
                        <view class="m-r-20" v-if="state.orderDetail?.status == OrderStatusEnum.pending &&
                        state.orderDetail?.payStatus == OrderPayStatusEnum.no &&
                        state.orderDetail?.shipStatus == OrderShipStatusEnum.no">
                            <uv-button type="error" size="small" text="取消订单" @click="handleCancelOrder"></uv-button>
                        </view>
                        <view class="m-r-20" v-if="state.orderDetail?.status == OrderStatusEnum.pending &&
                        state.orderDetail?.payStatus == OrderPayStatusEnum.no">
                            <uv-button type="primary" size="small" text="立即支付"
                                @click="handleRouteNavigateTo(`/pages/order/pay/pay?orderId=${state.orderId}&orderType=${state.orderDetail?.orderType}`)"></uv-button>
                        </view>
                        <view class="m-r-20" v-if="state.orderDetail?.status == OrderStatusEnum.pending &&
                        state.orderDetail?.payStatus >= OrderPayStatusEnum.yes &&
                        state.orderDetail?.shipStatus >= OrderShipStatusEnum.yes &&
                        state.orderDetail?.confirmStatus == OrderConfirmStatusEnum.receiptNotConfirmed">
                            <uv-button type="success" size="small" text="确认收货"
                                @click="handleConfirmReceiptGoods"></uv-button>
                        </view>
                        <view class="m-r-20"
                            v-if="state.orderDetail?.status == OrderStatusEnum.pending &&
                            state.orderDetail?.payStatus >= OrderPayStatusEnum.yes &&
                            state.orderDetail?.shipStatus >= OrderShipStatusEnum.yes &&
                            state.orderDetail?.confirmStatus >= OrderConfirmStatusEnum.confirmReceipt && state.orderDetail?.isComment == false">
                            <uv-button type="primary" size="small" text="立即评价"
                                @click="handleRouteNavigateTo(`/pages/subpackage/member/order/evaluate/evaluate?orderId=${state.orderId}`)"></uv-button>
                        </view>
                        <view class="m-r-20" v-if="state.orderDetail?.addAftersalesStatus">
                            <uv-button type="warning" size="small" text="申请售后"
                                @click="handleRouteNavigateTo(`/pages/subpackage/member/afterSales/apply/apply?orderId=${state.orderId}`)"></uv-button>
                        </view>
                        <view class="m-r-20" v-if="state.orderDetail?.billAftersalesId">
                            <uv-button type="warning" size="small" text="查看售后"
                                @click="handleRouteNavigateTo(`/pages/subpackage/member/afterSales/detail/detail?id=${state.orderDetail?.billAftersalesId}`)"></uv-button>
                        </view>
                        <view class="m-r-20"
                            v-if="state.orderDetail?.status == OrderStatusEnum.pending &&
                            state.orderDetail?.payStatus > OrderPayStatusEnum.no &&
                            state.orderDetail?.invoice &&
                            state.orderDetail?.invoice?.type == 1 && shopConfigStore?.config?.invoiceSwitch == ShowInvoiceEnum.yes">
                            <uv-button type="primary" size="small" text="申请发票" @click="handleApplyInvoice"></uv-button>
                        </view>
                    </view>
                    <uv-button type="primary" size="small" open-type="contact" bindcontact="showChat"
                        text="联系客服"></uv-button>
                </view>
            </view>

            <!-- 分享弹框 -->
            <CoreshopShare :show="state.showShare" :shareType="ShareEnum.addPinTuan"
                :goodsDetailData="state.shareDetailData" @handleClosePopup="handleToggleShowShare"></CoreshopShare>

        </view>
    </coreshop-page>
</template>
<script setup lang="ts">
    import { reactive, ref } from "vue";
    import { onLoad ,onShareAppMessage,onShareTimeline} from '@dcloudio/uni-app';
    import { queryOrderDetails, queryOrderPinTuanTeamInfo, queryCheckInvoice, queryOrderConfirm, queryOrderShippingList, queryCancelOrder } from '@/core/api';
    import type { Response } from '@/core/models';
    import { handleShowToast, handleRouteNavigateTo, getShareUrl } from '@/core/utils';
    import { OrderStatusEnum, OrderPayStatusEnum, ShareEnum, ShareClientEnum, ShareModelEnum, PayMethodCodeEnum, OrderShipStatusEnum, ShowInvoiceEnum, OrderConfirmStatusEnum, PinTuanStatusEnum, OrderAllStatusTypeEnum } from '@/core/enum';
    import { useShopConfigStore } from '@/core/store';
    import { shareUrl } from '@/core/consts';
    import GoodsDetailRecommend from '@/pages/components/goods-detail/components/goods-detail-recommend/goods-detail-recommend.vue';
    import uQRCode from '@/core/utils/uqrcode.js';
    import CoreshopShare from '@/components/coreshop-share/coreshop-share.vue';
    
    interface QueryParams {
        orderId : string;
        data ?: string;
    }

    // 获取项目配置
    const shopConfigStore = useShopConfigStore();

    const codePopup = ref();

    const state = reactive<{
        orderDetail : any;
        orderId : string;
        data : string;
        orderStatus : number;
        teamInfo : any;
        deliveryInfo : any;
        pickupCode : string;
        codeSrc : string;
        showShare : boolean;
        shareUrl:string;
        shareDetailData:any;
    }>({
        orderDetail: {},
        orderId: '',
        data: "",
        orderStatus: 0,
        teamInfo: {},
        deliveryInfo: {},
        pickupCode: "",
        codeSrc: "",
        showShare: false,
        shareUrl:"",
        shareDetailData:{},
    })

    onLoad((query : QueryParams) => {
        state.orderId = query?.orderId;
        state.data = query?.data;
        getOrderDetails();
    })

    const getOrderDetails = async () => {
        const orderDetail : Response<any> = await queryOrderDetails({
            id: state.orderId,
            data: state.data || '',
        });
        if (orderDetail.status) {
            state.orderDetail = orderDetail.data;
            /** 物流 */
            if (orderDetail.data?.delivery?.length > 0) {
                state.deliveryInfo = orderDetail.data?.delivery[0];
            }
            /** 是否拼团 */
            if (state.orderDetail.orderType == 2) {
                getOrderPinTuanTeamInfo(orderDetail.data.orderId)
            }
            /** 自提码 */
            if (state.orderDetail.ladingItem[0]) {
                state.pickupCode = state.orderDetail.ladingItem[0].id;
            }
            switch (orderDetail.data?.status) {
                case OrderStatusEnum.pending:
                    if (orderDetail.data?.payStatus == OrderPayStatusEnum.no) {
                        /** 待付款 */
                        state.orderStatus = 0;
                    } else if (orderDetail.data?.payStatus >= OrderPayStatusEnum.yes &&
                        orderDetail.data?.shipStatus == OrderShipStatusEnum.no) {
                        /** 待发货 */
                        state.orderStatus = 1;
                    } else if (orderDetail.data?.payStatus >= OrderPayStatusEnum.yes &&
                        orderDetail.data?.shipStatus == OrderShipStatusEnum.partialYes) {
                        /** 部分发货 */
                        state.orderStatus = 2;
                    } else if (orderDetail.data?.payStatus >= OrderPayStatusEnum.yes &&
                        orderDetail.data?.shipStatus >= OrderShipStatusEnum.yes &&
                        orderDetail.data?.confirmStatus == OrderConfirmStatusEnum.receiptNotConfirmed) {
                        /** 已发货 */
                        state.orderStatus = 2;
                    } else if (orderDetail.data?.payStatus >= OrderPayStatusEnum.yes &&
                        orderDetail.data?.shipStatus >= OrderShipStatusEnum.yes &&
                        orderDetail.data?.confirmStatus == OrderConfirmStatusEnum.confirmReceipt &&
                        !orderDetail.data?.isComment) {
                        /** 待评价 */
                        state.orderStatus = 3;
                    } else if (orderDetail.data?.payStatus >= OrderPayStatusEnum.yes &&
                        orderDetail.data?.shipStatus >= OrderShipStatusEnum.yes &&
                        orderDetail.data?.confirmStatus == OrderConfirmStatusEnum.confirmReceipt &&
                        orderDetail.data?.isComment) {
                        /** 已评价 */
                        state.orderStatus = 4;
                    }
                    break;
                case OrderStatusEnum.complete:
                    /** 已完成 */
                    state.orderStatus = orderDetail.data?.globalStatus;
                    break;
                case OrderStatusEnum.cancel:
                    /** 已取消 */
                    state.orderStatus = orderDetail.data?.globalStatus;
                    break;
            }
        } else {
            handleShowToast(orderDetail.msg)
        }
    } 
    
    /** 组合商品数据传入组件 */
    const hanldeCombinationGoodsData = (item : any) => {
        return {
            id: item.id,
            image: item.imageUrl,
            name: item.name,
            brief: item.addon,
        }
    }

    /** 获取拼团的数据 */
    const getOrderPinTuanTeamInfo = async (orderId : string) => {
        const teamInfo : Response<any> = await queryOrderPinTuanTeamInfo({ orderId, });
        if (teamInfo.status) {
            state.teamInfo = teamInfo?.data;
            state.shareDetailData = {
                pinTuanRule:{id:teamInfo?.data?.ruleId},
                id:state.orderDetail?.items[0]?.goodsId,  
                teamId:teamInfo?.data?.teamId,
                groupId:teamInfo?.data?.ruleId
            }
        } else {
            handleShowToast(teamInfo.msg)
        }
    }
    
    /** 取消订单 */
    const handleCancelOrder = () => {
        uni.showModal({
            title: '提示',
            content: '确认要取消订单吗？',
            async success(res : any) {
                if (res.confirm) {
                    const order : Response<any> = await queryCancelOrder({ id: state.orderId });
                    if (order.status) {
                        handleShowToast(order.msg, 'success', () => {
                            getOrderDetails();
                        })
                    } else {
                        handleShowToast(order.msg)
                    }
                }
            }
        });
    }

    /** 确认收货提示 */
    const handleConfirmReceiptGoods = (item : any) => {
        uni.showModal({
            title: "温馨提示",
            content: "您确认收货吗?",
            async success(res : any) {
                if (res.confirm) {
                    // #ifdef MP-WEIXIN
                    if (state.orderDetail.paymentCode === PayMethodCodeEnum.wechatpay && state.orderDetail?.paymentItem[0]?.status == OrderPayStatusEnum.yes) {
                        getOrderShippingList(state.orderDetail?.paymentItem[0]?.tradeNo)
                        return;
                    } else {
                        handleConfirmOrder();
                    }
                    // #endif 

                    // #ifndef MP-WEIXIN
                    handleConfirmOrder();
                    // #endif
                }
            }
        })
    }

    /** 查询当前订单是否接入微信发货信息管理 */
    const getOrderShippingList = async (id : string | number) => {
        const orderShippingList = await queryOrderShippingList({ id, });
        if (orderShippingList.status && orderShippingList.data) {
            if (wx.openBusinessView) {
                wx.openBusinessView({
                    businessType: 'weappOrderConfirm',
                    extraData: {
                        transaction_id: id,
                    },
                    success() {
                        handleConfirmOrder();
                    }
                });
            } else {
                handleShowToast('您的微信版本过低，请升级微信');
            }
        } else {
            handleConfirmOrder();
        }
    }

    /** 确认收货，确认订单 */
    const handleConfirmOrder = async () => {
        const orderConfirm = await queryOrderConfirm({ id: state.orderId });
        if (orderConfirm?.status) {
            handleShowToast('确认收货成功', 'success', () => {
                setTimeout(() => {
                    getOrderDetails();
                }, 2000)
            });
        } else {
            handleShowToast(orderConfirm?.msg);
        }
    }

    /** 发票下载到本地 */
    const handleSaveInvoice = () => {
        // #ifdef APP-PLUS || APP-PLUS-NVUE
        uni.downloadFile({
            url: state.orderDetail?.invoice?.fileUrl,
            success(res : any) {
                uni.saveImageToPhotosAlbum({
                    filePath: res.tempFilePath,
                    success() {
                        handleShowToast('操作成功', 'success')
                    },
                    fail() {
                        handleShowToast('发票保存失败')
                    }
                });
            },
            fail() {
                handleShowToast('下载失败')
            }
        })
        // #endif

        // #ifdef MP
        uni.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
                uni.downloadFile({
                    url: state.orderDetail?.invoice?.fileUrl,
                    success(res : any) {
                        uni.saveImageToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success() {
                                handleShowToast('操作成功', 'success')
                            },
                            fail() {
                                handleShowToast('发票保存失败')
                            }
                        });
                    },
                    fail() {
                        handleShowToast('下载失败')
                    }
                })
            }
        })
        // #endif
    }

    /** 查看物流信息 */
    const handleViewLogistics = (item : any) => {
        let address1 = state.orderDetail?.shipAreaName ? state.orderDetail?.shipAreaName : ''
        let address2 = state.orderDetail?.shipAddress ? state.orderDetail?.shipAddress : ''
        let address = address1 + address2;
        let params = encodeURIComponent(`code=${item.logiCode}&no=${item.logiNo}&add=${address}&mobile=${state.orderDetail?.shipMobile}`);
        handleRouteNavigateTo(`/pages/subpackage/member/order/expressDelivery/expressDelivery?params=${params}`)
    }

    /** 复制物流单号 */
    const handleCopyLogiNo = (num : number) => {
        uni.setClipboardData({
            data: num,
            success: function () {
                handleShowToast('复制成功')
            }
        });
    }

    /** 查看提货码 */
    const handleViewCode = () => {
        uQRCode.make({
            canvasId: 'qrcode',
            text: state.pickupCode,
            size: 200,
            backgroundColor: '#ffffff',
            foregroundColor: '#000000',
            fileType: 'jpg',
            correctLevel: uQRCode.errorCorrectLevel.H,
            success: (res : any) => {
                state.codeSrc = res;
            }
        })
        codePopup.value.open();
    }

    /** 申请发票 */
    const handleApplyInvoice = async () => {
        const checkInvoice : Response<any> = await queryCheckInvoice({ id: state.orderId });
        if (checkInvoice.status) {
            if (checkInvoice.data) {
                handleShowToast('此订单已经提交发票申请')
            } else {
                handleRouteNavigateTo(`/pages/subpackage/member/order/invoice/invoice?orderId=${state.orderId}`)
            }
        } else {
            handleShowToast(checkInvoice.msg)
        }
    }
    
    /** 邀请好友拼单 */
    const handleInviteFriends = async () => {
        /** 获取分享url */
        state.shareUrl = await getShareUrl({
            client: ShareClientEnum.wxMiNiProgram,
            url: shareUrl,
            type: ShareModelEnum.url,
            page: ShareEnum.addPinTuan,
            params: { 
                goodsId: state.orderDetail?.items[0]?.goodsId,  
                teamId:state.teamInfo.teamId,
                groupId:state.teamInfo.ruleId,
            }
        })
        state.showShare = true;
    }

    /** 分享弹框显示与否 */
    const handleToggleShowShare = () => {
        state.showShare = !state.showShare;
    }
    
    /** 分享 */
    onShareAppMessage(() => {
    	return {
    		title: state.orderDetail?.items[0]?.name,
    		imageUrl: state.orderDetail?.items[0]?.imageUrl,
    		path: state.shareUrl
    	}
    });
    onShareTimeline(() => {
    	return {
    		title: state.orderDetail?.items[0]?.name,
    		imageUrl: state.orderDetail?.items[0]?.imageUrl,
    		path: state.shareUrl
    	}
    });
</script>
<style lang="scss" scoped>
    @import './detail.scss';
</style>